//
//  LocationViewController.m
//  We365
//
//  Created by Pham Khuong Duy on 2/5/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "LocationViewController.h"
#import "SBJson.h"
#import <CoreLocation/CoreLocation.h>
#import "MainViewController.h"

@implementation LocationViewController
@synthesize table;
@synthesize search;
@synthesize webData;
@synthesize conn;
@synthesize items;
@synthesize lastIndex;

bool isSearching;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    int count = [self.navigationController.viewControllers count];
    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
        NSLog(@"View will disappear loading...count:");
        NSLog(@"%d",count);
        if (count == 1) {
            NSLog(@"Main View Will Display");
            NSLog(@"goBack function");
            [UIView beginAnimations:@"animation" context:nil];
            [UIView setAnimationDuration:1.0];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
            [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:NO];
            [self.navigationController popViewControllerAnimated:NO];
            [UIView commitAnimations];
            
        }
        else {
            NSLog(@"Not Found View Main");
        }
    }
    
    
    search.text = @"";
    [search resignFirstResponder];
    search.showsCancelButton = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    items = [[NSMutableArray alloc] init];
    
    UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle:@"Set" style:UIBarButtonItemStyleBordered target:self action:@selector(save:)];
    self.navigationItem.rightBarButtonItem = saveButton;
    [saveButton release];
    // Do any additional setup after loading the view from its nib.
    
    
    search.delegate = self;
    [[search.subviews objectAtIndex:0] removeFromSuperview];
    search.tintColor = [UIColor colorWithRed:53.0f/255.0f green:91.0f/255.0f blue:0.0f alpha:1.0f];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:BGSearch]];
    
    
}

- (void)viewDidUnload
{
    [self setTable:nil];
    [self setSearch:nil];
    [self setConn:nil];
    [self setWebData:nil];
    [self setItems:nil];
    [self setLastIndex:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)save:(id)sender
{
    isSearching = NO;
    UITableViewCell *cell = [table cellForRowAtIndexPath:lastIndex];
    if(cell == nil)
        return;
    
    NSLog(@"%@", cell.textLabel.text);
    NSString *locationName = [NSString stringWithString:cell.textLabel.text];
    
    NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=true", [locationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    conn = [NSURLConnection connectionWithRequest:request delegate:self];    
}

- (NSString *)title
{
    return @"Set Location";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:identifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];        
    }
    cell.textLabel.text = [items objectAtIndex:[indexPath row]];    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    if (indexPath.row % 2 == 0) {
        UIColor *colorEven = [UIColor colorWithRed:0.0f/255.0f green:168.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
        cell.textLabel.textColor = colorEven;
        cell.textLabel.shadowColor = [UIColor whiteColor];
        cell.textLabel.shadowOffset = CGSizeMake(1, 0.8f);
    }
    else {
        UIColor *colorOdd = [UIColor colorWithRed:255.0f/255.0f green:90.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
        cell.textLabel.textColor = colorOdd;
        cell.textLabel.shadowColor = [UIColor yellowColor];
        cell.textLabel.shadowOffset = CGSizeMake(1, 0.8f);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [search resignFirstResponder];
    int newRow = [indexPath row];
    int oldRow = (lastIndex != nil) ? [lastIndex row] : -1;
    if (newRow != oldRow) 
    {
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath]; 
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndex];
        oldCell.accessoryType = UITableViewCellAccessoryNone;
        lastIndex = indexPath; 
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row%2) {
        cell.backgroundColor = [UIColor clearColor];
        
    }
    else {
        // 192-200-214
        cell.backgroundColor = [UIColor colorWithRed:217.0f/255.0f green:228.0f/255.0f blue:249.0f/255.0f alpha:1.0f];
        
    }

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{    
    if(webData == nil)
        webData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    webData = nil;
    conn = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{    
    NSString *responseString = [[[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *root = [responseString JSONValue];    
    
    if(isSearching)
    {
        NSArray *results = [root objectForKey:@"predictions"];
        for (int i=0; i<[results count]; i++) {
            NSDictionary *result = [results objectAtIndex:i];
            NSString *item = (NSString *)[result objectForKey:@"description"];
            [items addObject:item];
        }
        [table reloadData];
    }
    else
    {
        NSArray *results = [root objectForKey:@"results"];
        NSDictionary *result = [results objectAtIndex:0];
        NSDictionary *geometry = [result objectForKey:@"geometry"];
        NSDictionary *location = [geometry objectForKey:@"location"];
        float lat = [[location objectForKey:@"lat"] floatValue];
        float lng = [[location objectForKey:@"lng"] floatValue];
        
        CLLocation *newLocation = [[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake(lat, lng)
                                                                 altitude:0
                                                       horizontalAccuracy:0
                                                         verticalAccuracy:0
                                                                timestamp:[NSDate date]];
        [MainViewController setLocation:newLocation];
        [newLocation release];
        [self.navigationController popViewControllerAnimated:YES];
    }    
    
    webData = nil;
    conn = nil;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if([searchText length] == 0)
    {
        [self resetSearch];
        [table reloadData];
        return;
    }
    [self handleSearch:searchText];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [search setShowsCancelButton:YES animated:YES];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    search.text = @"";
    [self resetSearch];
    [table reloadData];
    [search resignFirstResponder];
    [search setShowsCancelButton:NO animated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self handleSearch:[searchBar text]];
    [search resignFirstResponder];
    [search setShowsCancelButton:NO animated:YES];
}

- (void)resetSearch
{
    [items removeAllObjects];   
    lastIndex = nil;
}

- (void)handleSearch:(NSString *)key
{
    [self resetSearch];  
    isSearching = YES;
    key = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableString *urlString = [NSMutableString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&types=geocode&language=vi&sensor=true&key=AIzaSyDk4EnnRpfhd0knpKCMLffmifq5GzR7kOI", key];
        
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    conn = [NSURLConnection connectionWithRequest:request delegate:self];    
}

- (void)dealloc {
    [table release];
    [search release];
    [webData release];
    [conn release];
    [items release];
    [lastIndex release];
    [super dealloc];
}
@end
